<!-- 
    @file: 修改文章
    @auth: lizibin
 -->
<template>
    <div>
        <el-dialog v-model="compileArticleDialogFormVisible" title="" width="85%" @close="compileArticleCloseDialog(false)">
            <div class="addArticle_box">
                <h3 style="color: #2fa7b9;margin-bottom:10px;padding: 20px 20px;background-color: white;">
                    <el-icon style="margin-right: 10px;">
                        <EditPen />
                    </el-icon>
                    编辑文章
                </h3>
                <el-row :gutter="20">
                    <el-col :xs="24" :sm="24" :md="24" :lg="17" :xl="17">
                        <div class="write_abstract">
                            <h4>标题</h4>
                            <el-input v-model="articleInfo.articleTitle" placeholder="请输入文章标题" maxlength="50"
                                show-word-limit size="large" clearable />
                            <p>标示文章、作品内容的简明语句，填写醒目的</p>
                        </div>
                        <div class="write_abstract">
                            <!-- 富文本编辑器 -->
                            <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" />
                            <Editor style="height: 480px; overflow-y: hidden;" v-model="articleInfo.articleContent"
                                :defaultConfig="editorConfig" @onCreated="handleCreated" class="article" />
                        </div>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="7" :xl="7">
                        <div class="write_abstract">
                            <h4>摘要</h4>
                            <el-input v-model="articleInfo.articleDase" :autosize="{ minRows: 3, maxRows: 5 }"
                                maxlength="200" show-word-limit type="textarea" placeholder="请简单概述文章内容" clearable />
                            <p>筛选文章主要内容，让读者初步了解文章</p>
                        </div>
                        <div class="write_abstract">
                            <h4>缩略图</h4>
                            <el-input size="large" v-model="articleInfo.articleImgLitimg" placeholder="请点击上传图片或手动输入图片地址">
                                <template #append>
                                    <el-upload ref="uploadEle" class="upload-demo" :action="uploadURL"
                                        :on-success="handleAvatarSuccess" :before-upload="beforeUploadFunction"
                                        :show-file-list="false">
                                        <template #trigger>
                                            <el-button>上传图片</el-button>
                                        </template>
                                    </el-upload>
                                </template>
                            </el-input>
                            <p>注：点击上传的图片地址由系统生成，修改会导致图片失效</p>
                        </div>
                        <div class="write_abstract">
                            <h4>分类</h4>

                            <el-select v-model="articleInfo.articlePass" placeholder="请选择文章分类" size="large">
                                <el-option v-for="item in classifyInfo" :label="item.classifyName"
                                    :value="item.classifyId" />
                            </el-select>
                            <p>选择分类可让读者更便捷的查找文章</p>
                        </div>
                        <el-row :gutter="20">
                            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <div class="write_abstract">
                                    <h4>状态</h4>
                                    <el-select v-model="articleInfo.articleState" placeholder="文章状态" size="large">
                                        <el-option label="公开" value="1" />
                                        <el-option label="私密" value="2" />
                                    </el-select>
                                    <p>私密可视为草稿</p>
                                </div>
                            </el-col>
                            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                                <div class="write_abstract">
                                    <h4>评论</h4>
                                    <el-select v-model="articleInfo.commentState" placeholder="评论是否开启" size="large">
                                        <el-option label="开启" value="1" />
                                        <el-option label="关闭" value="2" />
                                    </el-select>
                                    <p>开启评论，开启新世界</p>
                                </div>
                            </el-col>
                        </el-row>
                        <div class="write_abstract" style="text-align: center;background: none;">
                            <el-button style="width: 50%;" plain color="#2fa7b9" @click="submitupdate">提交</el-button>
                            <p>注：普通用户修改内容需要再次等待管理员审核</p>
                            <p style="line-height: 10px;">（仅修改分类、状态、评论无须再次等待审核）</p>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import {
    ref,
    toRefs,
    onMounted,
    reactive,
    shallowRef,
    onBeforeUnmount,
    watch,
} from 'vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { GetArticleClass } from '@/api/foreground/index'
import { ClassArticleAdd, ClassArticleReduce, EditArtilceInfo } from '@/api/backstage/index'
import {
    Editor,
    Toolbar
} from '@wangeditor/editor-for-vue'

import {
    ElMessage,
    ElNotification,
} from 'element-plus'

import { ArticleInfo, EditArtilce } from "@/types/articleTypes";

import { useStore } from '@/store/index'
import { storeToRefs } from 'pinia'
const Store = useStore()
const { LoginInfo,AllArticleInfo } = storeToRefs(Store)
const { code: LoginCode, data: LoginData } = LoginInfo.value;
function loadData(state: any) {
    // 查询文章分类
    GetArticleClass().then(res => {
        state.classifyInfo = res.data
    })
}
const emit = defineEmits(['onCompileArticleCloseDialog'])

type Props = {
    compileArticleDialogFormVisible?: boolean,
    valueHtml?: ArticleInfo,
}
const props = withDefaults(defineProps<Props>(), {
    compileArticleDialogFormVisible: false,
    valueHtml: undefined,
})
watch(() => [props.compileArticleDialogFormVisible, props.valueHtml], (newval, oldval) => {
    state.compileArticleDialogFormVisible = newval[0] as boolean
    state.articleInfo = JSON.parse(JSON.stringify(newval[1]))
    // 别动就这样
    state.articleInfo.articleState = state.articleInfo.articleState.toString()
    state.articleInfo.commentState = state.articleInfo.commentState.toString()
})
const state = reactive<EditArtilce>({
    compileArticleDialogFormVisible: props.compileArticleDialogFormVisible,
    articleInfo: props.valueHtml as ArticleInfo,
    // 当前登录的用户信息
    userInfo: {
        userEmail: '',
        userIcon: '',
        userPass: '',
        userRegdate: '',
        userSignature: '',
        userId: -1,
        userType: -1,
        userName: '',
    },
    // 分类信息
    classifyInfo: [],
    // 缩略图上传到服务器的路径
    uploadURL: import.meta.env.VITE_HTTP + "upload/thumbnailUpload",
})
const { compileArticleDialogFormVisible, articleInfo, userInfo, classifyInfo, uploadURL } = toRefs(state)
// 以下是富文本框的相关配置

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

const toolbarConfig = {}
const editorConfig = {
    placeholder: '开始您的Write吧~',
    MENU_CONF: {
        uploadImage: {},
        uploadVideo: {},
        codeSelectLang: {},
    }
}
// watch(valueHtml.value, function (value, oldvalue) {
//     Prism.highlightAll();
// })

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！'
}

editorConfig.MENU_CONF['uploadImage'] = {
    // 上传图片的配置
    server: import.meta.env.VITE_HTTP + "upload/articleImgUpload",
    // 单个文件的最大体积限制，默认为 2M
    maxFileSize: 5 * 1024 * 1024, // 5M
    // 单个文件上传失败
    onFailed(file: any, res: any) {
        ElMessage.error(`${file.name} 上传失败`)
    },
    customInsert(res:any, insertFn:any) {                  // JS 语法
        // res 即服务端的返回结果
        // 从 res 中找到 url alt href ，然后插入图片
        insertFn(import.meta.env.VITE_HTTP + res.data.url)
    },
}
editorConfig.MENU_CONF['uploadVideo'] = {
    // 上传视频的配置
    server: import.meta.env.VITE_HTTP + 'upload/articleVideoUpload',
    // 单个文件的最大体积限制，默认为 20M
    maxFileSize: 100 * 1024 * 1024, // 100M
    // 单个文件上传失败
    onFailed(file: any, res: any) { // JS 语法
        ElMessage.error(`${file.name} 上传失败`)
    },
}
editorConfig.MENU_CONF['codeSelectLang'] = {
    // 代码语言
    codeLangs: [{
        text: 'CSS',
        value: 'css'
    },
    {
        text: 'HTML',
        value: 'html'
    },
    {
        text: 'XML',
        value: 'xml'
    },
    {
        text: 'Javascript',
        value: 'javascript'
    },
    {
        text: 'Typescript',
        value: 'typescript'
    },
    {
        text: 'JSX',
        value: 'jsx'
    },
    {
        text: 'Go',
        value: 'go'
    },
    {
        text: 'PHP',
        value: 'php'
    },
    {
        text: 'C',
        value: 'c'
    },
    {
        text: 'Python',
        value: 'python'
    },
    {
        text: 'Java',
        value: 'java'
    },
    {
        text: 'C++',
        value: 'cpp'
    },
    {
        text: 'C#',
        value: 'csharp'
    },
    {
        text: 'Visual Basic',
        value: 'visual-basic'
    },
    {
        text: 'SQL',
        value: 'sql'
    },
    {
        text: 'Ruby',
        value: 'ruby'
    },
    {
        text: 'Swift',
        value: 'swift'
    },
    {
        text: 'Bash',
        value: 'bash'
    },
    {
        text: 'Markdown',
        value: 'markdown'
    }
    ]
}

//挂载后加载数据
onMounted(() => {
    state.userInfo = LoginData.data[0]
    loadData(state);
});

// 图片上传格式、大小要求
const beforeUploadFunction = (rawFile: any) => {
    if (rawFile.type !== 'image/jpeg' &&
        rawFile.type !== 'image/jpg' &&
        rawFile.type !== 'image/png' &&
        rawFile.type !== 'image/gif') {
        ElMessage.error('仅支持图片格式.png | .jpg | .jpeg | .gif ')
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('仅支持大小不超过5MB的图片!')
        return false
    }
    return true
}

// 图片上传成功后执行的函数
const handleAvatarSuccess = (response: any) => {
    state.articleInfo.articleImgLitimg = response.data;
}

const compileArticleCloseDialog = (visible: any) => {
    // 关闭窗口
    emit("onCompileArticleCloseDialog", visible);
};

// 提交修改
const submitupdate = () => {
    // 太乱了，自己写
    // 判断是否有空数据 只判断标题和内容、
    if (state.articleInfo.articleTitle === '' || state.articleInfo.articleContent === '') {
        ElNotification({
            title: '提示',
            message: "文章标题和内容不允许为空！",
            type: 'error',
        })
        return
    }

    // 判断用户如果是管理员
    if (state.userInfo.userType === 0) {

    } else {
        // 不是的话需要审核
        state.articleInfo.articlePass = 1;
    }
    // 两个类型需要转一下
    state.articleInfo.articleState = Number(state.articleInfo.articleState)
    state.articleInfo.commentState = Number(state.articleInfo.commentState)
    EditArtilceInfo(state.articleInfo).then((res) => {
        // pina重新获取文章信息
        Store.getAllArticleInfo()
        // 判断文章分类是否修改
        if (state.articleInfo.articleClassifyId !== props.valueHtml.articleClassifyId) {
            // 增加现分类对应的文章数量  +1
            ClassArticleAdd({ classifyId: state.articleInfo.articleClassifyId })
            // 同时减少原先分类对应的文章数量
            ClassArticleReduce({ classifyId: props.valueHtml.articleClassifyId })
        }
        ElNotification({
            title: '提示',
            message: state.userInfo.userType == 0 ? "文章修改成功！" :
                "文章修改成功，等待管理员审核展示",
            type: 'success',
        })
        // 关闭修改窗口
        emit("onCompileArticleCloseDialog", false, res.code);
    })
}

</script>

<style scoped>
.addArticle_box {
    width: 100%;
    height: auto;
}

.write_abstract {
    background: white;
    text-align: left;
    padding: 10px 20px;
    margin-bottom: 10px;
}

.write_abstract h4 {
    line-height: 45px;
    color: #8f8f8f;
}

.write_abstract p {
    line-height: 35px;
    color: #8f8f8f;
    font-size: 12px;
}

.el-select {
    width: 100%;
}

/* 富文本编辑器样式 */
:deep(.w-e-bar) {
    background-color: #fff;
    color: #8b8b8b;
    font-size: 15px;
    padding: 15px 5px;
    border-bottom: 1px solid #ececec;
}

:deep(.w-e-bar-divider) {
    background-color: white;
}

:deep(.w-e-bar svg) {
    fill: #8b8b8b;
}

:deep(.w-e-bar-item button) {
    color: #8b8b8b;
}

:global(.w-e-full-screen-container) {
    z-index: 999 !important;
}

:deep(.w-e-bar-item .active) {
    background-color: #e8e8e8;
}

:deep(.el-dialog) {
    background: #F3F3F3;
}

:deep(.el-overlay-dialog) {
    top: -80px;
}
</style>